package com.songxh.shared.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.songxh.core.entity.UserContext;
import com.songxh.core.utils.LoginUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 处理新增和更新基础数据的填充，对应baseEntity
 *
 * @author songxh
 * @create 2023-01-06-14:59
 */
@Component
public class MyMetaHandler implements MetaObjectHandler {

    /**
     * 新增时填充
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        UserContext userContext = LoginUtils.get();
        if (getFieldValByName("cT", metaObject) == null) {
            this.strictInsertFill(metaObject, "cT", Date.class, new Date());
        }
        this.strictUpdateFill(metaObject, "uT", Date.class, new Date());
        this.strictInsertFill(metaObject, "version", Integer.class, 1);
        this.strictInsertFill(metaObject, "tenantId", String.class, "1");
        this.strictInsertFill(metaObject, "isDeleted", Integer.class, 0);
        //登录的时候没有用户信息，直接跳出
        if (userContext == null) {
            return;
        }
        if (getFieldValByName("cI", metaObject) == null) {
            this.strictInsertFill(metaObject, "cI", Long.class, userContext.getId());
        }
        if (getFieldValByName("cN", metaObject) == null || "".equals(getFieldValByName("cN", metaObject))) {
            this.strictInsertFill(metaObject, "cN", String.class, userContext.getAccount());
        }
        this.strictInsertFill(metaObject, "uI", Long.class, userContext.getId());
        this.strictInsertFill(metaObject, "uN", String.class, userContext.getAccount());
    }

    /**
     * 更新时填充
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        UserContext userContext = LoginUtils.get();
        this.strictUpdateFill(metaObject, "uT", Date.class, new Date());
        this.strictUpdateFill(metaObject, "tenantId", String.class, "1");
        if (userContext == null) {
            return;
        }
        this.strictUpdateFill(metaObject, "uI", Long.class, userContext.getId());
        this.strictUpdateFill(metaObject, "uN", String.class, userContext.getAccount());
    }
}
